package com.restphp.java.utils.string.encrypt;

import com.restphp.java.utils.string.core.StringUtils;
import org.apache.log4j.Logger;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5工具类.
 * Created by sofical on 2020/9/27.
 */
public class EncryptMd5Utils {
    /**
     * logger.
     */
    private static Logger logger = Logger.getLogger(EncryptMd5Utils.class);

    private static final ThreadLocal<MessageDigest> MD5_DIGEST_TL = new ThreadLocal<MessageDigest>() {
        @Override
        protected MessageDigest initialValue() {
            try {
                return MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException("Failed to initialize MD5 digest", e);
            }
        }
    };

    /**
     * MD5加密.
     * @param source 加密的文本.
     * @return 加密结果.
     */
    public static String encode(String source) {
        if (StringUtils.isBlank(source)) {
            return null;
        }

        try{
            MessageDigest md5 = MD5_DIGEST_TL.get();
            byte[] byteArray = source.getBytes("UTF-8");
            byte[] md5Bytes = md5.digest(byteArray);
            StringBuffer hexValue = new StringBuffer();
            for (int i=0; i<md5Bytes.length; i++){
                int val = md5Bytes[i] & 0xff;
                if (val < 16) {
                    hexValue.append("0");
                }
                hexValue.append(Integer.toHexString(val));
            }
            return hexValue.toString();
        }catch(Exception e){
            logger.error(e,e);
            return null;
        }
    }

    public static void main(String[] args) {
        System.out.println(encode("xxxxxxxxx"));
    }
}
